<template>
  <div id="map_container">
    <div id="map"></div>
    <div id="list">
      <el-table class="list-one" :data="tableData" @row-click="go" stripe>
        <el-table-column prop="name" label="医院名称"></el-table-column>
        <el-table-column prop="add" label="地址"></el-table-column>
      </el-table>

      <ul class="news-list">
        <li class="news" v-for="(link, index) in links" :key="index">{{ link.text }}</li>
      </ul>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import bus from '@/bus/bus';
import axios from 'axios'

window._AMapSecurityConfig = {
  securityJsCode: "62d3673292931360f7f664e4ef81cc82",
};
export default {
  data() {
    return {
      selectedPro: '北京市',
      links: [],
      map: null,
      autoOptions: {
        input: "",
      },
      searchPlaceInput: "",
      hospInput: "",
      begin: "",
      end: "",
      start: [],
      final: [],
      auto: null,
      placeSearch: null,
      district: null,
      polygons: [],
      showHeatOrNot: false,
      heatmap: null,
      heatmapList: null,
      drive: null,
      polyline: null,
      geocoder: null,
      e: null,
      tableData: []
    };
  },
  methods: {
    async loadaddress() {
      var url = '/医院地址/' + this.selectedPro + '.json'
      try {
        await axios.get(url).then(res => {
          this.tableData = res.data
        })
      } catch (error) {
        console.error('读取 JSON 文件时发生错误:', error)
      }
    },
    async news() {
      let url = this.selectedPro
      url = '/新闻栏/' + url + '.json'
      try {
        await axios.get(url).then(res => {
          this.links = res.data
        })
      } catch (error) {
        console.error('读取 JSON 文件时发生错误:', error)
      }
    },
    initMap() {
      AMapLoader.load({
        key: "be832aaacb575077b410510e9ee0218b", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.HawkEye",
          "AMap.MapType",
          "AMap.Geolocation",
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Driving",
          "AMap.Geocoder",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then(AMap => {
          this.map = new AMap.Map("map", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [121.473667, 31.230525], //初始化地图中心点位置
          });
          this.map.addControl(new AMap.Scale());
          this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.HawkEye());
          this.map.addControl(new AMap.MapType());
          this.map.addControl(new AMap.Geolocation());
          this.auto = new AMap.AutoComplete(this.autoOptions);

          this.geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          });
          this.drive = new AMap.Driving({
            policy: 0, //驾车路线规划策略，0是速度优先的策略
            map: this.map,
          });
          //this.drivingSearch = this.drive.search.bind(AMap.Driving);

          this.polyline = new AMap.Polyline({
            strokeColor: '#224456',
            strokeOpacity: 1,
            strokeWeight: 5,
            map: this.map,
          });

          this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
          }); //构造地点查询类
          this.auto.on("select", this.select);
        })
        .catch((e) => {
          this.e = e
          //console.log(e);
        });
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name); //关键字查询查询
      //this.drawBounds(e.poi.name);
      this.map.setZoom(16, true, 1);
    },
    // 行政区区域划分
    /*drawBounds(newValue) {
      //加载行政区划插件
      if (!this.district) {
        //实例化DistrictSearch
        var opts = {
          subdistrict: 1, //获取边界不需要返回下级行政区
          extensions: "all", //返回行政区边界坐标组等具体信息
          level: "district", //查询行政级别为 市
        };
        this.map.plugin(["AMap.DistrictSearch"], () => {
          this.district = new AMapLoader.DistrictSearch(opts);
        });
        // this.district = new AMap.DistrictSearch(opts)
      }
      //行政区查询
      this.district.search(newValue, (status, result) => {
        console.log(result);
        if (result != null) {
          this.feedBack("区域搜索成功", "success");
          if (this.polygons != null) {
            this.map.remove(this.polygons); //清除上次结果
            this.polygons = [];
          }
          var bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
              //生成行政区划polygon
              var polygon = new AMapLoader.Polygon({
                strokeWeight: 1,
                path: bounds[i],
                fillOpacity: 0.4,
                fillColor: "#80d8ff",
                strokeColor: "#0091ea",
              });
              this.polygons.push(polygon);
            }
          }
          this.map.add(this.polygons);
          this.map.setFitView(this.polygons); //视口自适应
        } else {
          this.feedBack("区域搜索失败", "error");
        }
      });
    },*/
    feedBack(msg, feedBackType) {
      this.$message({
        showClose: true,
        message: msg,
        type: feedBackType,
      });
    },
    showHeatMap() {
      this.map.plugin(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        var placeSearch = new AMapLoader.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          //map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        placeSearch.search("商场", (status, result) => {
          // console.log(result)
          this.getHotChartPos("商场", result);
        });
      });
      this.$notify({
        title: "成功",
        message: "热力图获取成果，但是由于电脑性能，我们仅加载部分数据",
        type: "success",
      });
    },
    getHotChartPos(detail, result) {
      let lengthSize = result.poiList.pageSize;
      const count = result.poiList.count;
      // const lengthPage = count / lengthSize
      if (lengthSize > count) {
        lengthSize = count;
      }
      for (var n = 0; n < lengthSize; n++) {
        // this.map.plugin(['AMap.PlaceSearch'], () => {
        //构造地点查询类
        var realSearch = new AMapLoader.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: n + 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          // map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        realSearch.search(detail, (status, result) => {
          // for (var j = 0; j < 50; j++) {
          // this.map.remove(this.map.getAllOverlays('marker'))
          //var centerPoint = [result.poiList.pois[j].location.lng,result.poiList.pois[j].location.lat]
          // console.log(result)
          //热力图
          this.showHatChart(result);
          // }
        });
      }
    },
    showHatChart(result) {
      var info = [];
      for (let i = 0; i < 50; i++) {
        info.push({
          lng: result.poiList.pois[i].location.lng,
          lat: result.poiList.pois[i].location.lat,
          count: 3 * 50 * Math.round(Math.random() * (10 - 2) + 2),
        });
      }
      this.map.plugin(["AMap.HeatMap"], () => {
        //初始化heatmap对象
        this.heatmap = new AMapLoader.HeatMap(this.map, {
          radius: 56, //给定半径
          opacity: [0, 0.5],
          /*,
gradient:{
0.5: 'blue',
0.65: 'rgb(117,211,248)',
0.7: 'rgb(0, 255, 0)',
0.9: '#ffea00',
1.0: 'red'
}
*/
        });
        //设置数据集
        this.heatmap.setDataSet({
          data: info,
          max: 100,
        });
        this.heatmapList.push(this.heatmap);
        this.heatmap.show();
      });
    },
    linePlan(begin, end) {
      // var points = [
      //   { keyword: begin, city: city },
      //   { keyword: end , city: city },
      // ];
      this.geocoder.getLocation([begin, end], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          if (result.geocodes.length > 0) {
            var firstGeocode1 = result.geocodes[0];
            var location1 = firstGeocode1.location;
            var firstGeocode2 = result.geocodes[1];
            var location2 = firstGeocode2.location;
            this.start.push(location1.lng, location1.lat);
            this.final.push(location2.lng, location2.lat);
          }
        }
      });

      // this.geocoder.getLocation([end], (status, result) => {  
      //   if (status === 'complete' && result.info === 'OK') {  
      //     if (result.geocodes.length > 0) {  
      //       var firstGeocode = result.geocodes[0];  
      //       var location = firstGeocode.location;  
      //       this.final.push(location.lng, location.lat);
      //     }
      //   }
      // });
    },
    linePlan1() {
      console.log(this.start);
      console.log(this.final);
      var start = this.start;
      var final = this.final;
      console.log(this.polyline.path)
      this.drive.search(start, final, (status, result) => {
        console.log('inner');
        // 绘制路径
        const path = result.routes[0].path;
        console.log(path);
        this.polyline.setPath(path);

      });
      console.log(this.polyline.path)
    },
    go(r, c, e) {
      console.log(c + e)
      this.hospInput = r.add
    }
  },
  mounted() {
    this.loadaddress()
    this.news()
    //DOM初始化完成进行地图初始化
    this.initMap();
  },
  created() {
    bus.$on('data-received', val => {
      this.selectedPro = val
      console.log(this.selectedPro)
    })
  },
  beforeDestroy() {
    bus.$off('data-received');
  },
  watch: {
    searchPlaceInput(newValue) {
      if (newValue != null) {
        console.log(newValue);
        this.placeSearch.search(newValue);
        //this.drawBounds(newValue);
        this.map.setZoom(16, true, 1);
        // this.linePlan(this.begin,this.end);
        // this.linePlan1();
      }
    },
    hospInput(newValue) {
      if (newValue != null) {
        console.log(newValue);
        this.placeSearch.search(newValue);
        //this.drawBounds(newValue);
        this.map.setZoom(16, true, 1);
        // this.linePlan(this.begin,this.end);
        // this.linePlan1();
      }
    },
    showHeatOrNot(newValue) {
      if (newValue) {
        this.showHeatMap();
      } else {
        this.heatmap.hide();
      }
    },
    selectedPro(newValue) {
      console.log(newValue)
      this.news()
      this.loadaddress()
    }
  },
};
</script>
<style scoped>

#map_container{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  height: 616px;
  margin: 0;

}

#map {
  width: 800px;
  height: 616px;
  margin: 0;
}

#list {
  width: 700px;
  height: 616px;
  background-color: white;
}
.list-one{
  width: 700px;
  height: 400px;
}

.news-list {
  overflow: hidden;
  width: 700px;
  height: 225px;
  white-space: nowrap;
  padding: 0;
  margin: 0;
  list-style: none;
}

.news {
  height: auto;
  margin-top: 10px;
  color: red;
  animation: scroll 5s linear infinite;
  padding: 10px;
}

@keyframes scroll {
  0% {
    transform: translateY(100%);
  }

  100% {
    transform: translateY(-650%);
  }
}
</style>